package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import domain.Order;
import domain.OrderItem;

public class OrderDao {
	public void addOrder(Order order) {
		Connection conn = null;
		try {
			conn = openConnection();
			conn.setAutoCommit(false);
			conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
			
			insertOrder(order, conn);
			for(OrderItem orderItem:order.getOrderItems())
			{
				PreparedStatement st = conn
				.prepareStatement("insert into orderItem(bookId,num,orderId) values(?,?,?)");
				st.setInt(1, orderItem.getBook().getBookId());
				st.setInt(2, orderItem.getNum());
				st.setInt(3, orderItem.getOrder().getOrderId());
				st.execute();
			}
			conn.commit();
		} catch (Exception e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	private void insertOrder(Order order, Connection conn) throws SQLException {
//		PreparedStatement st = conn
//				.prepareStatement("insert into [order](address) values(?)");
		PreparedStatement st = conn
		.prepareStatement("insert into orders(address) values(?)");
		st.setString(1, order.getAddress());
		st.execute();
		st = conn
		.prepareStatement("select max(orderId) from orders");
		ResultSet rs=st.executeQuery();
		if(rs.next())
		{
			order.setOrderId(rs.getInt(1));
		}
	}

	private Connection openConnection() throws ClassNotFoundException,
			SQLException {
		Connection conn;
//		Class.forName("net.sourceforge.jtds.jdbc.Driver");
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
//		conn = DriverManager.getConnection(
//				"jdbc:jtds:sqlserver://127.0.0.1:1433/bookshop2", "Xulin", "870207");
		conn = DriverManager.getConnection(
				"jdbc:mysql://127.0.0.1/bookshop?user=erik&password=870207");
		return conn;
	}
}
